package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.admin.entity.AdChannel;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdChannelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dtos.PageResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.admin.dtos.ChannelDto;
import com.heima.model.admin.dtos.ChannelListDto;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 * 频道信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-12-22
 */
@Service
public class AdChannelServiceImpl extends ServiceImpl<AdChannelMapper, AdChannel> implements AdChannelService {

    /**
     * 分页查询
     * */
    @Override
    public PageResult<AdChannel> findByPage(ChannelListDto dto) {
        // 分页
        Page<AdChannel> ipage = new Page<>(dto.getPage(), dto.getSize());
        // 条件
        LambdaQueryWrapper<AdChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(dto.getName()),AdChannel::getName, dto.getName());
        // 查询
        Page<AdChannel> page = this.page(ipage, queryWrapper);
        if(CollectionUtils.isEmpty(page.getRecords())){
            throw new LeadException(AppHttpCodeEnum.CHANNEL_NOT_EXIST);
        }
        return new PageResult<AdChannel>(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
    }

    @Override
    public void doSave(ChannelDto dto) {
        AdChannel adChannel = BeanHelper.copyProperties(dto, AdChannel.class);
        save(adChannel);
    }

    @Override
    public void doUpdate(ChannelDto dto) {
        AdChannel adChannelOld = this.getById(dto.getId());
        if(adChannelOld == null){
            throw new LeadException(AppHttpCodeEnum.CHANNEL_NOT_EXIST);
        }
        AdChannel adChannel = BeanHelper.copyProperties(dto, AdChannel.class);
        updateById(adChannel);
    }

    @Override
    public void doDelete(Integer id) {
        AdChannel adChannelOld = this.getById(id);
        if(adChannelOld == null){
            throw new LeadException(AppHttpCodeEnum.CHANNEL_NOT_EXIST);
        }
        this.removeById(id);
    }

    @Override
    public List<AdChannel> channels() {
        return this.list();
    }
}
